# -*- coding: utf-8 -*-
import json

from django.db.models import Count
from django.http import HttpResponse
from django.conf import settings as conf
from django.views import generic
from braces.views import JSONResponseMixin

from news.models import DailySummary, NewsDetail, NewsEdition, NewsCategory, NewsCluster, ClusterSummary, NewsStocksMap

# 每日新闻信息JSON展现

class DailySummaryApiView(generic.View):
    
    def get(self, *args, **kwargs):
        daily_summary_object = {}
        date = self.request.GET.get('date', '')
        category = self.request.GET.get('cat', '')
        edition = self.request.GET.get('edition', NewsEdition.MORNING)
        if date != '' and category != '':
            try:
                daily_summary = DailySummary.objects.get(date=date, 
                                                         category=category,
                                                         edition=edition)
            except DailySummary.DoesNotExist:
                daily_summary_object = {'Date': daily_summary.date.strftime('%Y-%m-%d'),
                                        'DocCount': daily_summary.doc_count,
                                        'DomainCount': daily_summary.domain_count,
                                        'TopKeywords': daily_summary.top_keywords,
                                       }
        return HttpResponse(json.dumps(daily_summary_object))

class NewsClusterApiView(generic.View):

    def get(self, *args, **kwargs):
        news_list = []
        date = self.request.GET.get('date', '')
        cluster_id = self.request.GET.get('cluster', '')
        if date != '':
            if cluster_id != '':
                news_clusters = NewsCluster.objects.filter(date=date,
                                                           cluster_id=cluster_id)
                news_list = [{'Date': cluster.news.published_time.strftime('%Y-%m-%d %H:%M:%S'),
                              'Title': cluster.news.title, 
                              'Publisher': cluster.news.publisher,
                              'Url': cluster.news.url,
                             } for cluster in news_clusters]
                return HttpResponse(json.dumps(news_list))
            else:
                #cluster_summaries = ClusterSummary.objects.filter(date=date).order_by('-doc_count')
                #summary_list = [{'Title': summary.display_news.title, 
                #                 'Publisher': summary.display_news.publisher,
                #                 'Url': summary.display_news.url,
                #                 'ClusterId': summary.cluster_id,
                #                 'ClusterDocCount': summary.doc_count,
                #                } for summary in cluster_summaries]
                #return HttpResponse(json.dumps(summary_list))

                latest_news = NewsDetail.objects.filter(date=date, 
                                                        category=NewsCategory.HEADLINE).order_by('-published_time')
                for news in latest_news:
                    if news.related_stocks.count() > 0:
                        related_stock = news.related_stocks.all()[0]
                        news_list.append({'Date': news.published_time.strftime('%Y-%m-%d %H:%M:%S'),
                                          'Title': news.title, 
                                          'Publisher': news.publisher,
                                          'Url': news.url,
                                          'RelatedStock': related_stock.short_name,
                                         })
                        if len(news_list) >= conf.API_DEFAULT_MAX_NUM_RESULTS:
                            break
        return HttpResponse(json.dumps(news_list))

class MostReportedStockApiView(generic.View):

    def get(self, *args, **kwargs):
        top_stock = []
        date = self.request.GET.get('date', '')
        if date != '':
            news_set = NewsDetail.objects.filter(date=date, 
                                                 category=NewsCategory.STOCK_NEWS, 
                                                 add_succeeded=True).distinct()
            news_stock_map = NewsStocksMap.objects.filter(news__in=news_set)
            top_stock = news_stock_map.values('stock').annotate(count=Count('stock')).order_by('-count')[:conf.API_DEFAULT_MAX_NUM_RESULTS]
            
        return HttpResponse(json.dumps(list(top_stock)))
